<?php

namespace App\Http\Controllers\Admin;

use App\Models\Node;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Admin;
use Illuminate\Mail\Message;
use Mail;
class IndexController extends Controller
{
    # 后台首页的展示
    public function index(){
        # 获取当前用户的所有权限
        $user = auth()->user()->role;
//        dump($user);die;
        # 判断他当前是否等于超级管理员，如果是那就全部显示
        if("admin" == auth()->user()->username){
            # 查询所有的权限
            $data = Node::where("is_menu","1")->get()->toArray();
        }else{
            # 模型关联
            $data = $user->nodes()->where("is_menu","1")->get()->toArray();
        }
        $data = subTree($data);
//        dump($data);die;
        return view("admin.index.index",compact("data"));
    }
    # 后台首页欢迎页面展示
    public function welcome(){
        # 登录成功后发送邮件通知用户
//        Mail::send("mali.user",["username"=>auth()->user()->username],function (Message $message){
//            #接收邮件用户
//            $message->to(auth()->user()->email,auth()->user()->username);
//            $time = date("Y-m-d H:i:s",time());
//            # 邮件的主题
//            $message->subject("好客租房提醒您，您在{$time}登录成功");
//        });

        return view("admin.index.welcome");
    }
    # 个人信息展示
    public function messages(){
        $user_id = auth()->user()->id;
        $user_list = Admin::find($user_id);
//        dump($user_list);die;
        return view("admin.index.messages",["data"=>$user_list]);
    }
    # 个人信息的展示
    public function edits(int $id){
        $user_list = Admin::find($id);
//        dump($user_list);die;
        return view("admin.index.edits",["data"=>$user_list]);
    }
    # 个人信息的修改数据处理
    public function msgupdata(int $id,Request $request){
        $data = $this->validate($request,[
            "username" => "required|unique:admins,username,".$id,
            "truename" => "required",
            "password" => "nullable|confirmed",
            "phone"    => "required|regex:/^1[3-9]\d{9}$/",
            "email"    => "required|email",
            "sex"      => "required"
        ]);
//        dump($data);

        Admin::where("id",$id)->update($data);
        return redirect( route("admin.messages"))->with("success","个人信息修改成功");
    }
    # 退出登录
    public function logout(){
        # 清空session里面的数据
        auth()->logout();
        # 跳转页面
        return redirect( route("admin.login"))->with("success","退出登录成功");
    }
}
